import React, {useRef, useState} from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { getOvertimeSporadicList,deleteOdd,saveOdd,overWorkOddBpm } from '../service';
import moment from 'moment';
import {PlusOutlined} from '@ant-design/icons';
import {Tag,Tooltip,Button,message,Popconfirm,Divider} from 'antd';
import AddForm from './components/AddForm';
import store from 'store2';
import {connect} from 'umi';

const TableList = ({currentUser}) => {
  const actionRef = useRef();
  const [visible, setVisible] = useState(false);
  const [loading,setLoading] = useState(false);

  const columns = [
    {
      title: '申请时间',
      dataIndex: 'createTime',
      hideInSearch: true,
      render: (text) => {
        return text !== '-' ? moment(text).format('YYYY-MM-DD') : ''
      },
    },
    {
      title: '申请人',
      dataIndex: 'oprationName',
    },
    {
      title: '申请人工号',
      dataIndex: 'oprationId',
    },
    {
      title: '加班名称',
      dataIndex: 'overworkName',
    },
    {
      title: '加班人员',
      dataIndex: 'list',
      hideInSearch: true,
      align:'center',
      width: 300,
      render:(text)  => (
        <>
          {text?.map((item,index) => {
              let temp = item.orgName + "-" + item.unitName + "-" + item.userName + "-" + item.userId;
              return  <Tooltip overlayStyle={{maxWidth: 500}} title={temp} key={index}>
                <Tag style={{marginTop:'5px'}} color={'#68b377'} key={index}>
                  {item.userName}
                </Tag>
              </Tooltip>
            }
          )}
        </>
      )
    },
    {
      title: '加班时间(月份)',
      dataIndex: 'overworkTime',
      hideInSearch: true,
      render: (text) => {
        return text !== '-' ? moment(text).format('YYYY-MM') : '';
      },
    },
    {
      title: '附件',
      dataIndex: 'uploadFile',
      hideInSearch: true,
      ellipsis:true,
      render:(text,record) => {
        return <a href={record.uploadFile} target="_blank">查看附件</a>
      }
    },
    {
      title: '审批状态',
      dataIndex: 'status',
      hideInSearch: true,
      valueEnum: {
        0: {text: '待发起', status: 'Default'},
        1: {text: '审批中', status: 'Processing'},
        2: {text: '审批通过', status: 'Success'},
        3: {text: '审批拒绝', status: 'Warning'},
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      align:'center',
      render: (item, record) => (
        <>
          {(record.status === 1) && <>
            <a onClick={() => sendBpm(record.id)}>发起BPM</a>
            <Divider type="vertical"/>
            <Popconfirm title={`是否确认删除?`} onConfirm={() => delOvertime(record.id)} okText="是" cancelText="否">
              <a>删除</a>
            </Popconfirm>
          </>}
          {(record.status !== 1 && record.checkUrl) && <><a onClick={() => window.open(record.checkUrl)}>审批详情</a></>}
        </>
      ),
    }
  ];

  const delOvertime = (id) => {
    deleteOdd(id).then(res => {
      if(res.flag){
        message.success('删除成功！');
        actionRef.current.reload();
      }else{
        message.error(res.error);
      }
    });
  };

  const sendBpm = (id) => {
    overWorkOddBpm(id).then(res => {
      if (res.flag) {
        message.success(`bpm发起成功！`);
        window.open(res.data);
      } else {
        message.error(`bpm错误:` + res.error);
      }
      setLoading(false);
    });
  };

  const handleCancel = () => {
    setVisible(false);
  };

  const handleSubmit = (values) => {
    setLoading(true);
    saveOdd(values).then((res) => {
      if(res.flag){
        store.remove(`attendance-overtimeSporadic-` + currentUser.mobile);
        setVisible(false);
        message.success('发送成功！');
        actionRef.current.reload();
      }else{
        message.error(`保存错误：`+res.error);
      }
      setLoading(false);
    })
  };

  return (
    <PageHeaderWrapper>
      <ProTable
        actionRef={actionRef}
        rowKey="id"
        request={(params) => getOvertimeSporadicList(params)}
        columns={columns}
        toolBarRender={(action, {selectedRows}) => [
          <Button key='0' type="primary" onClick={() => setVisible(true)}><PlusOutlined/>新增</Button>,
        ]}
      />
      <AddForm
        loading={loading}
        visible={visible}
        onCancel={handleCancel}
        onSubmit={handleSubmit}
      />
    </PageHeaderWrapper>
  )
};
export default connect(({user}) => ({currentUser:user.currentUser}))(TableList)
